<template>
  <div class="role-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card class="search-card">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="queryParams.roleName"
              placeholder="请输入角色名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="角色编码" prop="roleCode">
            <el-input
              v-model="queryParams.roleCode"
              placeholder="请输入角色编码"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="角色状态" clearable>
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button icon="el-icon-edit" :disabled="single" @click="handleUpdate">修改</el-button>
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        :disabled="multiple" 
        @click="handleDelete"
      >删除</el-button>
      <el-button icon="el-icon-setting" :disabled="single" @click="handlePermission">分配权限</el-button>
    </div>
    
    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="roleList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="角色编号" align="center" prop="id" width="100" />
        <el-table-column label="角色名称" align="center" prop="roleName" :show-overflow-tooltip="true" />
        <el-table-column label="角色编码" align="center" prop="roleCode" :show-overflow-tooltip="true" />
        <el-table-column label="显示顺序" align="center" prop="roleSort" width="100" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-dropdown>
              <span class="el-dropdown-link">
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handlePermission(scope.row)">分配权限</el-dropdown-item>
                  <el-dropdown-item @click="handleDataScope(scope.row)">数据权限</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    
    <!-- 角色表单对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog title="分配权限" v-model="permissionOpen" width="800px" append-to-body>
      <div class="permission-container">
        <div class="permission-tools">
          <div class="tool-buttons">
            <el-button size="small" icon="el-icon-s-unfold" @click="expandAll">展开全部</el-button>
            <el-button size="small" icon="el-icon-s-fold" @click="collapseAll">折叠全部</el-button>
            <el-button size="small" icon="el-icon-check" @click="selectAll">全选</el-button>
            <el-button size="small" icon="el-icon-close" @click="deselectAll">取消全选</el-button>
          </div>
        </div>
        
        <!-- 权限树 -->
        <div class="permission-tree-container">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionTree"
            :props="defaultProps"
            node-key="id"
            show-checkbox
            default-expand-all
            highlight-current
            @check="handlePermissionCheck"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <i :class="getPermissionIcon(data.type)" class="permission-icon"></i>
                <span class="permission-label">{{ node.label }}</span>
                <span class="permission-code">{{ data.permCode }}</span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelPermission">取 消</el-button>
          <el-button type="primary" @click="submitPermission">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据权限对话框 -->
    <el-dialog title="数据权限" v-model="dataScopeOpen" width="600px" append-to-body>
      <el-form :model="dataScopeForm" ref="dataScopeFormRef" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="dataScopeForm.roleName" disabled />
        </el-form-item>
        <el-form-item label="权限范围" prop="dataScope">
          <el-select v-model="dataScopeForm.dataScope" placeholder="请选择数据权限范围" style="width: 100%">
            <el-option label="全部数据权限" value="1" />
            <el-option label="自定义数据权限" value="2" />
            <el-option label="本部门数据权限" value="3" />
            <el-option label="本部门及以下数据权限" value="4" />
            <el-option label="仅本人数据权限" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-if="dataScopeForm.dataScope === '2'">
          <el-tree
            ref="deptTreeRef"
            :data="deptTree"
            :props="deptProps"
            node-key="id"
            show-checkbox
            default-expand-all
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDataScope">取 消</el-button>
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 加载状态
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 总条数
const total = ref(0)
// 角色表格数据
const roleList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 是否显示权限分配弹出层
const permissionOpen = ref(false)
// 是否显示数据权限弹出层
const dataScopeOpen = ref(false)
// 日期范围
const dateRange = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleName: undefined,
  roleCode: undefined,
  status: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  roleName: undefined,
  roleCode: undefined,
  roleSort: 0,
  status: 1,
  menuIds: [],
  remark: undefined
})

// 权限相关数据
const permissionTree = ref([])
const permissionTreeRef = ref(null)
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 权限对象
const permissionForm = reactive({
  roleId: undefined,
  permissionIds: []
})

// 表单校验
const rules = {
  roleName: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '角色编码不能为空', trigger: 'blur' }
  ],
  roleSort: [
    { required: true, message: '显示顺序不能为空', trigger: 'blur' }
  ]
}

// 部门树引用
const deptTreeRef = ref(null)

// 数据权限表单
const dataScopeForm = reactive({
  roleId: undefined,
  roleName: '',
  dataScope: '1',
  deptIds: []
})

// 部门树配置
const deptProps = {
  children: 'children',
  label: 'name'
}

// 模拟部门树数据
const deptTree = ref([
  {
    id: 1,
    name: '总公司',
    children: [
      {
        id: 2,
        name: '研发部',
        children: [
          {
            id: 4,
            name: '前端组'
          },
          {
            id: 5,
            name: '后端组'
          }
        ]
      },
      {
        id: 3,
        name: '销售部',
        children: [
          {
            id: 6,
            name: '国内销售组'
          },
          {
            id: 7,
            name: '海外销售组'
          }
        ]
      }
    ]
  }
])

// 模拟数据
const mockRoleList = [
  {
    id: 1,
    roleName: '超级管理员',
    roleCode: 'admin',
    roleSort: 1,
    status: 1,
    createTime: '2023-01-01 00:00:00'
  },
  {
    id: 2,
    roleName: '普通用户',
    roleCode: 'user',
    roleSort: 2,
    status: 1,
    createTime: '2023-01-02 00:00:00'
  },
  {
    id: 3,
    roleName: '访客',
    roleCode: 'visitor',
    roleSort: 3,
    status: 0,
    createTime: '2023-01-03 00:00:00'
  }
]

// 模拟权限树数据
const mockPermissionTree = [
  {
    id: 1,
    name: '系统管理',
    type: 'menu',
    permCode: 'system:manage',
    children: [
      {
        id: 11,
        name: '用户管理',
        type: 'menu',
        permCode: 'system:user',
        children: [
          {
            id: 111,
            name: '用户查询',
            type: 'button',
            permCode: 'system:user:query'
          },
          {
            id: 112,
            name: '用户新增',
            type: 'button',
            permCode: 'system:user:add'
          },
          {
            id: 113,
            name: '用户修改',
            type: 'button',
            permCode: 'system:user:edit'
          },
          {
            id: 114,
            name: '用户删除',
            type: 'button',
            permCode: 'system:user:delete'
          }
        ]
      },
      {
        id: 12,
        name: '角色管理',
        type: 'menu',
        permCode: 'system:role',
        children: [
          {
            id: 121,
            name: '角色查询',
            type: 'button',
            permCode: 'system:role:query'
          },
          {
            id: 122,
            name: '角色新增',
            type: 'button',
            permCode: 'system:role:add'
          },
          {
            id: 123,
            name: '角色修改',
            type: 'button',
            permCode: 'system:role:edit'
          },
          {
            id: 124,
            name: '角色删除',
            type: 'button',
            permCode: 'system:role:delete'
          }
        ]
      }
    ]
  },
  {
    id: 2,
    name: '系统监控',
    type: 'menu',
    permCode: 'monitor:manage',
    children: [
      {
        id: 21,
        name: '日志管理',
        type: 'menu',
        permCode: 'monitor:log',
        children: [
          {
            id: 211,
            name: '操作日志',
            type: 'menu',
            permCode: 'monitor:log:operation'
          },
          {
            id: 212,
            name: '登录日志',
            type: 'menu',
            permCode: 'monitor:log:login'
          }
        ]
      },
      {
        id: 22,
        name: '服务监控',
        type: 'menu',
        permCode: 'monitor:server',
        children: []
      }
    ]
  }
]

// 查询角色列表
const getList = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    roleList.value = mockRoleList
    total.value = mockRoleList.length
    loading.value = false
  }, 500)
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.roleName = undefined
  form.roleCode = undefined
  form.roleSort = 0
  form.status = 1
  form.menuIds = []
  form.remark = undefined
}

// 权限表单重置
const resetPermission = () => {
  permissionForm.roleId = undefined
  permissionForm.permissionIds = []
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryParams.roleName = undefined
  queryParams.roleCode = undefined
  queryParams.status = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加角色'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const roleId = row?.id || ids.value[0]
  // 模拟获取角色详情
  const roleInfo = mockRoleList.find(item => item.id === roleId)
  if (roleInfo) {
    Object.assign(form, roleInfo)
  }
  open.value = true
  title.value = '修改角色'
}

// 提交按钮
const submitForm = () => {
  // 模拟提交
  ElMessage.success(form.id ? '修改成功' : '新增成功')
  open.value = false
  getList()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 删除按钮操作
const handleDelete = (row) => {
  const roleIds = row?.id ? [row.id] : ids.value
  
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 角色状态修改
const handleStatusChange = (row) => {
  const text = row.status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确认要${text}该角色吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟修改状态
    ElMessage.success(`${text}成功`)
  }).catch(() => {
    row.status = row.status === 1 ? 0 : 1
  })
}

// 分配权限
const handlePermission = (row) => {
  resetPermission()
  // 设置当前角色ID
  permissionForm.roleId = row?.id || ids.value[0]

  // 加载权限树
  permissionTree.value = mockPermissionTree
  
  // 获取当前角色权限
  // 模拟已分配的权限ID
  const assignedPermissions = [11, 111, 112, 21, 211]
  
  permissionOpen.value = true
  
  // 等待DOM更新后设置选中状态
  setTimeout(() => {
    permissionTreeRef.value.setCheckedKeys(assignedPermissions)
  }, 100)
}

// 提交权限
const submitPermission = () => {
  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
  permissionForm.permissionIds = [...checkedKeys, ...halfCheckedKeys]
  
  // 模拟提交
  ElMessage.success('权限分配成功')
  permissionOpen.value = false
}

// 取消权限分配
const cancelPermission = () => {
  permissionOpen.value = false
  resetPermission()
}

// 数据权限
const handleDataScope = (row) => {
  // 重置表单
  dataScopeForm.roleId = row.id
  dataScopeForm.roleName = row.roleName
  dataScopeForm.dataScope = '1' // 默认全部数据权限
  dataScopeForm.deptIds = []
  
  dataScopeOpen.value = true
  
  // 等待DOM更新后设置选中状态
  setTimeout(() => {
    if (deptTreeRef.value && dataScopeForm.dataScope === '2') {
      // 模拟已分配的部门ID
      const assignedDepts = [2, 4]
      deptTreeRef.value.setCheckedKeys(assignedDepts)
    }
  }, 100)
}

// 提交数据权限
const submitDataScope = () => {
  // 如果是自定义数据权限，则获取选中的部门ID
  if (dataScopeForm.dataScope === '2' && deptTreeRef.value) {
    dataScopeForm.deptIds = [
      ...deptTreeRef.value.getCheckedKeys(),
      ...deptTreeRef.value.getHalfCheckedKeys()
    ]
  }
  
  // 模拟提交
  ElMessage.success('数据权限设置成功')
  dataScopeOpen.value = false
}

// 取消数据权限
const cancelDataScope = () => {
  dataScopeOpen.value = false
}

// 获取权限图标
const getPermissionIcon = (type) => {
  switch (type) {
    case 'menu':
      return 'el-icon-menu'
    case 'button':
      return 'el-icon-magic-stick'
    default:
      return 'el-icon-folder'
  }
}

// 展开所有
const expandAll = () => {
  permissionTreeRef.value.expandAll()
}

// 折叠所有
const collapseAll = () => {
  permissionTreeRef.value.store.nodesMap = {}
  permissionTreeRef.value._initDefaultCheckedNodes()
}

// 全选
const selectAll = () => {
  const allNodes = []
  const getAllKeys = (data) => {
    data.forEach(item => {
      allNodes.push(item.id)
      if (item.children && item.children.length) {
        getAllKeys(item.children)
      }
    })
  }
  getAllKeys(permissionTree.value)
  permissionTreeRef.value.setCheckedKeys(allNodes)
}

// 取消全选
const deselectAll = () => {
  permissionTreeRef.value.setCheckedKeys([])
}

// 权限选中状态变化
const handlePermissionCheck = () => {
  // 可以在这里处理权限选中状态变化
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.role-container {
  padding: 0;
}

.search-container {
  margin-bottom: 20px;
}

.search-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.action-container {
  margin-bottom: 20px;
}

.table-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  margin-left: 8px;
}

/* 权限树样式 */
.permission-container {
  padding: 10px;
}

.permission-tools {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.tool-buttons {
  display: flex;
  gap: 10px;
}

.permission-tree-container {
  height: 400px;
  overflow-y: auto;
  border: 1px solid #e6e6e6;
  padding: 10px;
  border-radius: 4px;
}

.tree-node {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.permission-icon {
  margin-right: 5px;
  font-size: 16px;
}

.permission-label {
  margin-right: 8px;
}

.permission-code {
  color: #909399;
  font-size: 12px;
}
</style> 